import Taro from '@tarojs/taro'
import { observable, action } from "mobx";
import { uploadFile } from "../utils/http";


export interface File {
  name: string;
  url: string;
  originalUrl: string;
}

export default class FileStore {
  @observable files: Array<File> = []
  @observable files2: Array<File> = []

  @action
  clear() {
    this.files = []
    this.files2 = []
  }

  // 图片上传
  @action
  async uploadImg(files: File[], operationType: string) {
    switch(operationType) {
      case 'add':
        const result = <File>await uploadFile(files[files.length - 1].url)
        const oldFiles = this.files.filter((item: File) => item)
        this.files = [...oldFiles, result]
        break;
      case 'remove':
        this.files = files
        break;
      default:
        break;
    }
  }

  // 图片预览
  @action
  preview(_: number, file: File) {
    Taro.previewImage({
      current: file.url, // 当前显示图片的http链接
      urls: this.files.map(img => img.url) // 需要预览的图片http链接列表
    })
  }

  // 图片预览2
  @action
  preview2(url, files: File[]) {
    Taro.previewImage({
      current: url, // 当前显示图片的http链接
      urls: files.map(img => img.url) // 需要预览的图片http链接列表
    })
  }

  @action
  async chooseMessageFile() {
    const { errMsg, tempFiles } = await Taro.chooseMessageFile({counts: 1, type: 'file'})
    if (errMsg === 'chooseMessageFile:ok') {
      const result = <File>await uploadFile(tempFiles[0].path)
      result.name = tempFiles[0].name
      this.files2 = [result]
    }
  }
}
